<?php
/**
 * Created by PhpStorm.
 * User: Kyle
 * Date: 2019/9/3
 * Time: 15:13
 */

namespace app\backend\controller;


use app\base\controller\AdminBaseController;
use app\common\model\Config;
use app\common\model\TopicAnswer;
use app\common\model\TopicLog;
use app\common\model\TopicQuestion;
use app\common\services\WechatService;
use app\logic\TopicLogic;
use app\logic\WechatLogic;
use think\Exception;
use think\facade\Request;
use think\facade\View;

class Topic extends AdminBaseController
{
    public function index(){

        $category = Request::param('category',0);
        $title = Request::param('title','');

        $where = [];
        if(!empty($category)){
            array_push($where,['category','=',$category]);
        }
        if(!empty($title)){
            array_push($where,['title','like','%'.$title.'%']);
        }

        $topicList = \app\common\model\Topic::where(['is_deleted'=>0])
            ->where($where)
            ->order(['weight'=>'asc','created_at'=>'desc'])->paginate(15,false,[
                'query'=>['category'=>$category,'title'=>$title]
            ]);

        $ids = [];
        foreach ($topicList as &$v){
            $ids[] = $v['topic_id'];
        }

        if($ids){
            //查询总的访问人数和测评数据
            $topicTotalLog = topicLog::whereIn("topic_id",$ids)->field(['topic_id','count(user_id) as count'])->group('topic_id')->select()->toArray();
            $topicTotalUserLog = topicLog::whereIn("topic_id",$ids)->field("count(DISTINCT(user_id)) as count , topic_id")->group('topic_id')->select()->toArray();

            //php获取今日开始时间戳和结束时间戳
            $today_start=mktime(0,0,0,date('m'),date('d'),date('Y'));
            $today_end=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
            $topicTodayLog = topicLog::whereIn("topic_id",$ids)->whereBetween('created_at',[$today_start,$today_end])->field(['topic_id','count(user_id) as count'])->group('topic_id')->select()->toArray();
            $topicTodayUserLog = topicLog::whereIn("topic_id",$ids)->whereBetween('created_at',[$today_start,$today_end])->field("count(DISTINCT(user_id)) as count , topic_id")->group('topic_id')->select()->toArray();
            //php获取昨日起始时间戳和结束时间戳
            $yesterday_start=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
            $yesterday_end=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
            $topicYesterdayLog = topicLog::whereIn("topic_id",$ids)->whereBetween('created_at',[$yesterday_start,$yesterday_end])->field(['topic_id','count(user_id) as count'])->group('topic_id')->select()->toArray();
            $topicYesterdayUserLog = topicLog::whereIn("topic_id",$ids)->whereBetween('created_at',[$yesterday_start,$yesterday_end])->field("count(DISTINCT(user_id)) as count , topic_id")->group('topic_id')->select()->toArray();
            //php获取近一小时起始时间戳和结束时间戳
            $hour_start= time() - 3600;
            $hour_end= time();
            $topicHourLog = topicLog::whereIn("topic_id",$ids)->whereBetween('created_at',[$hour_start,$hour_end])->field(['topic_id','count(user_id) as count'])->group('topic_id')->select()->toArray();
            $topicHourUserLog = topicLog::whereIn("topic_id",$ids)->whereBetween('created_at',[$hour_start,$hour_end])->field("count(DISTINCT(user_id)) as count , topic_id")->group('topic_id')->select()->toArray();
            foreach ($topicList as &$v){
                $v['totalCount'] = 0;
                $v['totalUserCount'] = 0;
                $v['topicTodayCount'] = 0;
                $v['totalTodayUserCount'] = 0;
                $v['topicYesterdayCount'] = 0;
                $v['totalYesterdayUserCount'] = 0;
                $v['topicHourCount'] = 0;
                $v['totalHourUserCount'] = 0;
                if($topicTotalLog){
                    foreach ($topicTotalLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){$v['totalCount'] = $log['count'];break;}
                    }
                    unset($log);
                }
                if($topicTotalUserLog){
                    foreach ($topicTotalUserLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){$v['totalUserCount'] = $log['count'];break;}
                    }
                    unset($log);
                }

                if($topicTodayLog){
                    foreach ($topicTodayLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){$v['topicTodayCount'] = $log['count'];break;}
                    }
                    unset($log);
                }
                if($topicTodayUserLog){
                    foreach ($topicTodayUserLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){$v['totalTodayUserCount'] = $log['count'];break;}
                    }
                    unset($log);
                }

                if($topicYesterdayLog){
                    foreach ($topicYesterdayLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){$v['topicYesterdayCount'] = $log['count'];break;}
                    }
                    unset($log);
                }
                if($topicYesterdayUserLog){
                    foreach ($topicYesterdayUserLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){$v['totalYesterdayUserCount'] = $log['count'];break;}
                    }
                    unset($log);
                }

                if($topicHourLog){
                    foreach ($topicHourLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){$v['topicHourCount'] = $log['count'];break;}
                    }
                    unset($log);
                }
                if($topicHourUserLog){
                    foreach ($topicHourUserLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){$v['totalHourUserCount'] = $log['count'];break;}
                    }
                    unset($log);
                }
            }

        }



        $this->assign('categoryList',(new \app\common\model\TopicCate())->getList());
        $this->assign('category',$category);
        $this->assign('title',$title);
        $this->assign('list',$topicList);
        $this->assign('page',$topicList->render());


        //判断当前是否请求过图文素材的更新
        $mediaInfo = Config::where(['config_key'=>array(
            'wechat_thumb_media_id','wechat_img_url'
        )])->select()->toArray();
        $setStatus = true;
        if(empty($mediaInfo)){$setStatus = false;}
        foreach ($mediaInfo as &$m){
            if(empty($m['config_value']) || $m['config_value'] == null){$setStatus = null;}
        }
        $this->assign('setStatus',$setStatus);
        return $this->fetch();
    }

    public function add(){
        $this->assign('categoryList',(new \app\common\model\TopicCate())->getList());
        $this->assign('sex',implode(",",array_keys(\app\common\model\Topic::$_sex)));
        $this->assign('constellations',implode(",",array_keys(\app\common\model\Topic::$_constellations)));
        return $this->fetch();
    }

    public function save(){
        $request = Request::post();

        //验证
        (new TopicLogic())->validateTopic($request);

        //存储数据库
        (new TopicLogic())->save($request);
    }

    public function edit(){
        $id = Request::param('id',0);
        if(empty($id)|| !is_numeric($id+0)){throw new Exception('数据错误');}
        $topicInfo = \app\common\model\Topic::where('topic_id',$id)->find()->toArray();
        if(!$topicInfo){throw new Exception('数据错误');}
        $this->assign('topicInfo',$topicInfo);
        $this->assign('sex',implode(",",array_keys(\app\common\model\Topic::$_sex)));
        $this->assign('constellations',implode(",",array_keys(\app\common\model\Topic::$_constellations)));
        $this->assign('categoryList',(new \app\common\model\TopicCate())->getList());
        return $this->fetch();
    }

    public function del(){
        $id = Request::param('id',0);
        if(empty($id)|| !is_numeric($id+0)){wapAjaxReturn(400);}

        $topicInfo = \app\common\model\Topic::where('topic_id',$id)->find();
        if(!$topicInfo){wapAjaxReturn(400);}
        $topicInfo->is_deleted = 1;
        $topicInfo->save();
        wapAjaxReturn(0);
    }

    public function deal_attr(){
        $id = Request::param('id',0);
        $type = Request::param('type','');
        $status = Request::param('status',-1);
        if(empty($id)|| !is_numeric($id+0)){wapAjaxReturn(400);}
        if(!in_array($status,[0,1])){wapAjaxReturn(400);}

        $topicInfo = \app\common\model\Topic::where('topic_id',$id)->find();
        if(!$topicInfo){wapAjaxReturn(400);}
        switch ($type){
            case 'banner':
                $topicInfo->is_banner = $status;
                break;
            case 'top':
                $topicInfo->is_recommend = $status;
                break;
            case 'icon_type':
                $topicInfo->icon_type = $status;
                break;
            case 'is_publish':
                $topicInfo->is_publish = $status;
                break;
        }

        $topicInfo->save();
        wapAjaxReturn(0);

    }

    public function question(){
        $data = TopicQuestion::where(['topic_id'=>Request::param('id'),'is_deleted'=>0])->select()->toArray();
        View::assign('topic_id',Request::param('id'));
        View::assign('data',$data);
        return View::fetch();
    }
    public function answer(){
        $data = TopicAnswer::where(['topic_id'=>Request::param('id'),'is_deleted'=>0])->select()->toArray();
        View::assign('data',$data);
        View::assign('topic_id',Request::param('id'));
        return View::fetch();
    }
    public function saveQuestion(){
        if(Request::isPost()){
            $question = new TopicQuestion();
            $post = Request::post();
            $post['question_options'] = json_encode(
                array(
                    'content'=>$post['content'],
                    'score'=>$post['score'],
                )
            );
            if(!empty($post['id'])){
                $save = $question->allowField(true)->save($post,['id'=>$post['id']]);
                $save ? wapAjaxReturn(0,'更新成功',[],'/admin/topic/question') : wapAjaxReturn(400,'更新失败');

            }else{
                $post['created_at'] =time();
                $save = $question->allowField(true)->save($post);
                $save ? wapAjaxReturn(0,'新增成功',[],'/admin/topic/question') : wapAjaxReturn(400,'新增失败');

            }
        }

        $id = Request::param('id',0);
        if(!empty($id)){
            $data = TopicQuestion::where(['id'=>$id,'is_deleted'=>0])->find()->toArray();
            if($data != null ){
                if(!empty($data['question_options'])){
                    $data['question_options'] = json_decode($data['question_options'],true);
                }
            }
        }else{$data['question'] = '';$data['question_sort'] = 0;}
        View::assign('data',$data);
        View::assign('topic_id',Request::param('topic_id',0));
        View::assign('id',Request::param('id',0));
        return View::fetch();
    }
    public function saveAnswer(){
        if(Request::isPost()){
            $question = new TopicAnswer();
            $post = Request::post();
            if(!empty($post['id'])){
                $save = $question->allowField(true)->save($post,['id'=>$post['id']]);
                $save ? wapAjaxReturn(0,'更新成功',[],'/admin/topic/answer') : wapAjaxReturn(400,'更新失败');

            }else{
                $post['created_at'] =time();
                $save = $question->allowField(true)->save($post);
                $save ? wapAjaxReturn(0,'新增成功',[],'/admin/topic/answer') : wapAjaxReturn(400,'新增失败');

            }
        }

        $id = Request::param('id',0);
        if(!empty($id)){
            $data = TopicAnswer::where(['id'=>$id,'is_deleted'=>0])->find()->toArray();
        }else{$data['answer_img'] = '';$data['min_score'] = 0;$data['max_score'] = 0;}
        View::assign('data',$data);
        View::assign('topic_id',Request::param('topic_id',0));
        View::assign('id',Request::param('id',0));
        return View::fetch();
    }
    public function dealAttr(){
        $id = Request::post('id',0);
        $type = Request::post('type',0);
        switch ($type){
            case 1:
                $topicInfo = TopicQuestion::where('id',$id)->find();
                if(!$topicInfo){wapAjaxReturn(400);}
                $topicInfo->is_deleted = 1;$topicInfo->save();break;
            case 2:
                $topicInfo = TopicAnswer::where('id',$id)->find();
                if(!$topicInfo){wapAjaxReturn(400);}
                $topicInfo->is_deleted = 1;$topicInfo->save();break;
         }
         wapAjaxReturn(0,'success');
    }



}